#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "hi_gpio.h"
#include "hi_io.h"
#include "hi_adc.h"
#include "hi_errno.h"

// --- 宏定义修改区域 ---
#define LED_INTERVAL_TIME_US 200000
#define LED_TASK_STACK_SIZE 4096
#define LED_TASK_PRIO 25

#define LED_TEST_GPIO 11       // 原为10，现改为11 (输出)
#define SKEW_DETECT_GPIO 10    // 原为11，现改为10 (输入)

#define SKEW_DETECT_ON 1
#define SKEW_DETECT_OFF 0

enum LedState {
    LED_ON = 0,
    LED_OFF,
    LED_SPARK,
};

// --- 初始化函数 ---
static void SkewDetectInit(void)
{
    // 1. 初始化 LED (现在是 GPIO 11)
    IoTGpioInit(LED_TEST_GPIO);
    
    // 【修改点2】复用功能必须匹配 GPIO 11
    hi_io_set_func(LED_TEST_GPIO, HI_IO_FUNC_GPIO_11_GPIO); 
    
    IoTGpioSetDir(LED_TEST_GPIO, IOT_GPIO_DIR_OUT);
    hi_io_set_pull(LED_TEST_GPIO, HI_IO_PULL_UP);
    IoTGpioSetOutputVal(LED_TEST_GPIO, LED_OFF);

    // 2. 初始化 传感器 (现在是 GPIO 10)
    IoTGpioInit(SKEW_DETECT_GPIO);
    
    // 【修改点3】复用功能必须匹配 GPIO 10
    hi_io_set_func(SKEW_DETECT_GPIO, HI_IO_FUNC_GPIO_10_GPIO);
    
    IoTGpioSetDir(SKEW_DETECT_GPIO, IOT_GPIO_DIR_IN);
    hi_io_set_pull(SKEW_DETECT_GPIO, HI_IO_PULL_UP);
}

// --- 任务处理函数 (逻辑保持不变) ---
static void *SkewDetectTask(const char *arg)
{
    unsigned char ucType;
    (void)arg;
    
    while (1) {
        ucType = 0;
        // 从新的引脚(GPIO 10)读取状态
        IoTGpioGetInputVal(SKEW_DETECT_GPIO, &ucType);
        printf("SKEW_DETECT_GPIO %d\n", ucType);
        
        if(ucType == SKEW_DETECT_ON)
        {
            // 控制新的引脚(GPIO 11)亮灯
            IoTGpioSetOutputVal(LED_TEST_GPIO, LED_ON);
        }
        else
        {
            IoTGpioSetOutputVal(LED_TEST_GPIO, LED_OFF);
        }
        
        usleep(LED_INTERVAL_TIME_US);
    }
    return NULL;
}

// --- 线程入口函数 ---
static void SkewDetectEntry(void)
{
    osThreadAttr_t attr;
    
    SkewDetectInit();
    
    attr.name = "SkewDetectTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0;
    attr.stack_mem = NULL;
    attr.stack_size = LED_TASK_STACK_SIZE;
    attr.priority = LED_TASK_PRIO;
    
    if (osThreadNew((osThreadFunc_t)SkewDetectTask, NULL, &attr) == NULL) {
        printf("[SkewDetectEntry] Failed to create SkewDetectTask!\n");
    }
}

SYS_RUN(SkewDetectEntry);